package com.letv.so.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.letv.mms.cache.factory.CacheFactory;
import com.letv.so.bean.ExtranetAlbumBean;
import com.letv.so.constants.Constants;
import com.letv.so.service.CacheService;
import com.letv.so.service.QueryDataService;
import com.letv.so.util.SoKeyUtil;
import com.letv.so.util.StringUtil;

/**
 * 获取cbase数据接口
 * 
 * @author wenjian
 * 
 */
public class QueryCbaseServiceImpl implements QueryDataService {
	private static Logger logger = Logger
			.getLogger(QueryCbaseServiceImpl.class);
	
    private CacheService soCacheClient;
    private CacheService xmemcachedClient;
    private boolean useOldMemcachedClient = false;
    
    private CacheService getCacheService() {
        
        return useOldMemcachedClient ? soCacheClient : xmemcachedClient;
    }

	/**
	 * 根据soKey取得单条数据
	 * 
	 * @param soKey
	 * @return
	 */
	public String get(String soKey) {
		long beginTime = System.currentTimeMillis();
		String result = null;
		try {
			result = (String) getCacheService().get(soKey);
		} catch (Exception e) {
			logger.error("get val from cbase error : soKey=" + soKey,e);			
			try {
	            result = (String) getCacheService().get(soKey);
			} catch (Exception ee) {
				logger.error("get val from cbase error : soKey=" + soKey,ee);
			}
		}
		
		long markTime = System.currentTimeMillis();
		logger.debug("query cbase soKey=" + soKey + ", consume time="
				+ (markTime - beginTime));
		return result;
	}
	
	/**
	 * 根据soKey取得多条数据
	 * 
	 * @param soKey
	 * @return
	 */
	public Map<String,Object>  getMulti(String[] soKeys) {
		String arrays = Arrays.toString(soKeys);
		long beginTime = System.currentTimeMillis();
		Map<String,Object> result = null;
		try {
		    result = getCacheService().getMulti(soKeys);
		} catch (Exception e) {
			logger.error("getMulti vals from cbase error : soKeys=" + arrays,e);			
			try {
	            result = getCacheService().getMulti(soKeys);
			} catch (Exception ee) {
				logger.error("getMulti vals from cbase error : soKeys=" + arrays,ee);
				//ee.printStackTrace();
			}
		}
		long markTime = System.currentTimeMillis();
		logger.debug(" getMulti. keys= " +arrays +", consume time="
				+ (markTime - beginTime));
		return result;
	}
	
	public String get(String sid, String soKey) {
		long beginTime = System.currentTimeMillis();
		String result = null;
		try {
            result = (String) getCacheService().get(soKey);
		} catch (Exception e) {
			logger.error(sid+" ,get val from cbase error : soKey=" + soKey,e);			
			try {
	            result = (String) getCacheService().get(soKey);
			} catch (Exception ee) {
				logger.error(sid+" ,get val from cbase error : soKey=" + soKey,ee);
				//ee.printStackTrace();
			}
		}
		long markTime = System.currentTimeMillis();
		logger.debug(sid+" ,query cbase soKey=" + soKey + ", consume time=["
				+ (markTime - beginTime));
		return result;
	}

    /**
     * get thrift serialize from cbase
     * @param key String, cbase key
     * @return byte[], thrift serialize.return null if no data or has errors
     */
    public byte[] getThrift(String key) {
        if(StringUtils.isBlank(key)) {
            return null;
        }
        byte[] result = null;
        try {
            result = (byte[])CacheFactory.getCache().get(key, null);
        } catch(Exception e) {
            logger.error("get thrift serialize cp info from cbase has errors,key=" + key, e);
        }
        return result;
    }

	/**
	 * 根据soKeyList取得多条数据
	 * 
	 * @param soKey
	 * @return
	 */
	public List<String> get(String sid, List<String> soKeyList) {
		long beginTime = System.currentTimeMillis();
		List<String> resList = new ArrayList<String>();
		for (String soKey : soKeyList) {
			String result = get(soKey);
			if (!StringUtils.isBlank(result)) {
				resList.add(result);
			} else {
				logger.info(sid+" ,query cbase soKey=" + soKey + ", result is null");
			}
		}
		long markTime = System.currentTimeMillis();
		logger.debug(sid+" ,query cbase total consume time=" + (markTime - beginTime));
		return resList;
	}
	
	/**
	 * 根据soKeyList取得多条数据
	 * 
	 * @param soKey
	 * @return
	 */
	public List<String> getMulti(String sid, List<String> soKeyList) {
		long beginTime = System.currentTimeMillis();
		List<String> resList = new ArrayList<String>();
		String[] soKeys = soKeyList.toArray(new String[soKeyList.size()]);  
		Map<String,Object> rtns = this.getMulti(soKeys);
		if (rtns != null) {
			for (String key:soKeys){
				if (rtns.get(key) !=null && !StringUtils.isBlank(rtns.get(key).toString())) {
					resList.add(rtns.get(key).toString());
				} else {
					logger.info(sid+" ,query cbase soKey=" + key + ", result is null");
				}
			}
		}
		return resList;
	}

    public void setUseOldMemcachedClient(boolean useOldMemcachedClient) {
        this.useOldMemcachedClient = useOldMemcachedClient;
    }

    public void setSoCacheClient(CacheService soCacheClient) {
        this.soCacheClient = soCacheClient;
    }

    public void setXmemcachedClient(CacheService xmemcachedClient) {
        this.xmemcachedClient = xmemcachedClient;
    }

    /**
     * 解析sokey获得leso专辑ID
     * 
     * @param soKey
     * @return
     */
    public String getLesoAid(String id) {
        String lesoAid = SoKeyUtil.getSoKeySegment(id,2);
        if (Constants.VRS_ALBUM_PERFIX.indexOf(id) == 0 ) { // sokey如果对应的是vrs的专辑需要一次查询，才能获得lesoAid
            String soKey = "newleso_la_" + lesoAid;
            String soData = this.get(soKey);
            if (StringUtil.isBlank(soData)) {
                return null;
            }
            ExtranetAlbumBean eAlbum = JSON.parseObject(soData, ExtranetAlbumBean.class);
            lesoAid = eAlbum.getAid();

        }
        return lesoAid;
    }
}
